package com.ruoyi.proposal.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.proposal.domain.Proposal;
import com.ruoyi.proposal.dto.ProposalQueryDTO;
import com.ruoyi.proposal.service.ProposalService;
import com.ruoyi.proposal.vo.ProposalVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 提案财务审核API控制器
 * 对应前端finance.vue页面
 */
@RestController
@RequestMapping("/proposal/finance")
public class ProposalFinanceController extends BaseController {

    @Autowired
    private ProposalService proposalService;

    /**
     * 查询需要财务审核的提案列表
     * 对应前端finance.vue中的fetchData方法
     * @param queryDTO 查询条件
     * @return 提案列表
     */
    @PreAuthorize("@ss.hasPermi('proposal:finance:list')")
    @GetMapping("/list")
    public TableDataInfo listFinanceProposals(ProposalQueryDTO queryDTO) {
        com.github.pagehelper.PageHelper.startPage(queryDTO.getPageNum(), queryDTO.getPageSize());
        List<ProposalVO> proposals = proposalService.findFinanceProposals(queryDTO);
        return getDataTable(proposals);
    }

    /**
     * 更新财务节省金额
     * 对应前端finance.vue中表格的输入框
     * @param proposal 提案对象
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:finance:edit')")
    @Log(title = "财务审核", businessType = BusinessType.UPDATE)
    @PutMapping("/savings")
    public AjaxResult updateFinanceSavings(@RequestBody Proposal proposal) {
        try {
            // 调用服务更新节省金额
            proposalService.updateSavings(convertToDTO(proposal));
            return AjaxResult.success("节省金额更新成功");
        } catch (Exception e) {
            return AjaxResult.error("节省金额更新失败: " + e.getMessage());
        }
    }

    /**
     * 将Proposal对象转换为ProposalDTO
     * @param proposal 提案对象
     * @return 提案DTO对象
     */
    private com.ruoyi.proposal.dto.ProposalDTO convertToDTO(Proposal proposal) {
        com.ruoyi.proposal.dto.ProposalDTO dto = new com.ruoyi.proposal.dto.ProposalDTO();
        org.springframework.beans.BeanUtils.copyProperties(proposal, dto);
        return dto;
    }
}